# -*- coding:utf-8 -*-
from .models import *

# 还是留下FileCacheManager吧. 多个Manager可以共用一个Bucket.
# 而且transporter还是有价值的.
class FileCacheManager(object):
    def __init__(self, bucket='default', transporter=None):
        if isinstance(bucket, (str, unicode)):
            bucket_name = bucket
            try:
                bucket = FileCacheBucket.objects.get(name=bucket_name)
            except FileCacheBucket.DoesNotExist:
                bucket = FileCacheBucket(name=bucket_name)
                bucket.save()

        self.bucket = bucket
        self.transporter = transporter

    def get(self, uri, when_not_exist=['fetch']):
        """
        :param uri:
        :param when_not_exist: 'fetch' or a func(uri, dest), or a list of such stuffs.
        :return: a file cache record.
        """
        if not isseq(when_not_exist):
            when_not_exist = [when_not_exist]
        replaced_wne_list = []
        for wne in when_not_exist:
            if wne == 'fetch':
                if self.transporter is not None:
                    replaced_wne_list.append(self.transporter.fetch)
            else:
                replaced_wne_list.append(wne)

        return self.bucket.get(uri, when_not_exist=replaced_wne_list)

    def put(self):
        pass

    def clear_cache(self, by='access_dt', ensure_free_size=None):
        return self.bucket.clear_cache(by=by, ensure_free_size=ensure_free_size)


class NoCacheManager(object):
    def __init__(self, rootdir):
        self.rootdir = P(rootdir)

    def get(self, uri):
        filepath = os.path.join(self.rootdir, uri)
        if os.path.exists(filepath):
            return filepath
        else:
            raise ValueError("Uri: %s does not exist!" % uri)

    def put(self):
        pass